from sqlalchemy.orm import Session
from sqlalchemy import Column, Date, Integer, String, Index, TEXT, DECIMAL
from sqlalchemy import and_, func, or_

from common.database import Base
from common.database import SessionMixin


class QosProcessIo(Base, SessionMixin):
    __tablename__ = 'qos_process_io'
    report_time = Column(Date, nullable=False, comment="数据上报时间")
    hostname = Column(String(40), nullable=False, comment="主机名称")
    ip = Column(String(20), nullable=False, comment="主机地址")
    pid = Column(Integer, nullable=False, comment="进程编号")
    user = Column(String(40), nullable=False, comment="系统用户")
    disk_read = Column(DECIMAL(10, 2), nullable=False, comment="读速率")
    disk_write = Column(DECIMAL(10, 2), nullable=False, comment="写速率")
    io = Column(DECIMAL(10, 2), nullable=False, comment="io使用率")
    command = Column(TEXT, nullable=False, comment="进程名称")

    __table_args__ = (
        Index('idx_qos_process_io_uuid', 'uuid', unique=True),
        Index('idx_qos_process_io_report_time', 'report_time'),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    # @classmethod
    # def get_req_time_avg_aggregate(cls, db: Session, data_month):
    #     first_day, last_day = get_month_range(data_month)
    #     return db.query(cls).with_entities(cls.domain_name, cls.verb, cls.url,
    #                                        func.sum(cls.request_count).label('request_count'),
    #                                        func.round(func.avg(cls.avg_req_time), 2).label('avg_req_time')).filter(
    #         cls.log_date.between(first_day, last_day)).group_by(cls.domain_name, cls.verb, cls.url).having(
    #         func.sum(cls.request_count) > 100).to_dict()
    #
    # @classmethod
    # def get_http_status_count_aggregate(cls, db: Session, data_month):
    #     first_day, last_day = get_month_range(data_month)
    #     return db.query(cls).with_entities(cls.domain_name, cls.verb, cls.url,
    #                                        func.sum(cls.request_count).label('request_count'),
    #                                        func.sum(
    #                                            cls.http_status_1xx + cls.http_status_2xx + cls.http_status_3xx).label(
    #                                            'http_status_2xx'),
    #                                        func.sum(cls.http_status_4xx).label('http_status_4xx'),
    #                                        func.sum(cls.http_status_5xx).label('http_status_5xx')).filter(
    #         cls.log_date.between(first_day, last_day)).group_by(cls.domain_name, cls.verb, cls.url).having(
    #         func.sum(cls.request_count) > 100).to_dict()
